<template>
  <div>
    <!-- 导航面包屑 -->
    <a-breadcrumb style="margin-bottom: 10px">
      <a-breadcrumb-item>
        <icon-menu-unfold />
      </a-breadcrumb-item>
      <a-breadcrumb-item>报警管理</a-breadcrumb-item>
      <a-breadcrumb-item>报警事件</a-breadcrumb-item>
    </a-breadcrumb>

    <a-card>
      <!-- 查询条件表单 -->
      <a-row>
        <a-form :model="searchModel" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }" label-align="left" auto-label-width>
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item label="事件状态">
                <a-select v-model="searchModel.triggerStatus" placeholder="全部状态" allow-clear>
                  <a-option value="0">发生中</a-option>
                  <a-option value="10">已恢复</a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="报警等级">
                <a-select v-model="searchModel.triggerLevel" placeholder="全部等级" allow-clear>
                  <a-option value="100">一级报警</a-option>
                  <a-option value="200">二级报警</a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-divider style="height: 32px" direction="vertical" />
            <a-col :flex="'86px'" style="text-align: right">
              <a-space :size="18">
                <a-button type="primary" @click="search">
                  <template #icon>
                    <icon-search />
                  </template>
                  {{ '查询' }}
                </a-button>
                <a-button @click="reset">
                  <template #icon>
                    <icon-refresh />
                  </template>
                  {{ '重置' }}
                </a-button>
              </a-space>
            </a-col>
          </a-row>
        </a-form>
      </a-row>

      <!-- 分割线 -->
      <a-divider style="margin-top: 0" />

      <!-- 表格内容 -->
      <a-table :loading="loading" size="medium" row-key="id" ref="tableRef"
               :pagination="pagination" @page-change="onPageChange" @page-size-change="onPageSizeChange"
               :bordered="{ wrapper: true, cell: true }" :columns="columns" :data="renderData">
        <!-- 报警级别 -->
        <template #triggerLevel="{ record }">
          <a-tag v-if="record.triggerLevel == 100" color="rgb(var(--red-6))">一级报警</a-tag>
          <a-tag v-else color="rgb(var(--primary-6))">二级报警</a-tag>
        </template>

        <!-- 状态 -->
        <template #triggerStatus="{ record }">
          <a-tag v-if="record.triggerStatus == 0" color="rgb(var(--red-6))">发生中</a-tag>
          <a-tag v-else color="rgb(var(--green-6))">已恢复</a-tag>
        </template>

        <!-- 操作 -->
        <template #operate="{ record }">
          <a-button size="small" type="text" v-if="record.triggerStatus != 10" status="success" @click="handleConfirm(record)">
            {{ '确认' }}
          </a-button>
          <a-button size="small" type="text" @click="handleDetail(record)">
            {{ '详情' }}
          </a-button>
          <a-button size="small" v-if="record.triggerStatus != 10 && record.triggerStatus != -1" type="text" status="danger" @click="handleCreateOrder(record)">
            <template #icon>
              <icon-plus />
            </template>
            {{ '创建工单' }}
          </a-button>
        </template>
      </a-table>

      <!-- 事件确认弹框 -->
      <a-modal width="450px" title="事件确认" v-model:visible="operateModalModel.visible" @ok="handleOperateModelOk" @cancel="handleOperateModelCancle">
        <a-row :gutter="24">
          <a-col :span="24">
            <a-form ref="formRef" auto-label-width :model="operateModalModel.formModel" label-align="right" :rules="operateModalModel.rules">
              <!-- 事件名称 -->
              <a-form-item field="triggerName" label="事件名称">
                {{ operateModalModel.formModel.triggerName }}
              </a-form-item>

              <!-- 报警状态 -->
              <a-form-item field="triggerStatus" label="事件状态">
                <a-select v-model="operateModalModel.formModel.triggerStatus" placeholder="请选择事件状态" allow-clear>
                  <a-option value="10">已恢复</a-option>
                </a-select>
              </a-form-item>
            </a-form>
          </a-col>
        </a-row>
      </a-modal>

      <!-- 报警详情抽屉 -->
      <a-drawer :width="600" title="报警详情" :visible="formDrawer.visible" hide-cancel @cancel="handleFormCancel" @ok="handleFormCancel" unmountOnClose :mask-closable="false">
        <a-descriptions
            :value-style="{ width: '600px' }"
            :label-style="{
            color: 'rgb(var(--color-neutral-10))'
          }"
            :data="detailDataList"
            :column="1"
            size="large"
        >
          <template #value="{ value }">
            <a-skeleton v-if="formDrawer.loading" :animation="true">
              <a-skeleton-line :rows="1" />
            </a-skeleton>
            <span v-else>{{ value }}</span>
          </template>
        </a-descriptions>
      </a-drawer>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import useLoading from '../../utils/loading';
import { BasePagination } from '../../apis/common';
import { listTrigger } from '../../apis/call';
import dayjs from 'dayjs';
import { useRouter } from 'vue-router';
import { DescData } from '@arco-design/web-vue';

const router = useRouter();
const { loading, setLoading } = useLoading(true);

// 生成查询条件对象
const generateSearchModel: any = () => {
  return {
    // 事件状态
    triggerStatus: '',
    // 报警等级
    triggerLevel: ''
  };
};

// 查询表单对象
const searchModel = ref(generateSearchModel());

// 表格数据
const renderData = ref<any[]>([]);

// 表格分页参数
const pagination: any = reactive({ ...BasePagination() });

// 设置表格列
const columns = computed<any[]>(() => [
  {
    title: '事件名称',
    dataIndex: 'triggerName',
    slotName: 'triggerName',
    align: 'center',
    width: 160
  },
  {
    title: '所属站点',
    dataIndex: 'stationName',
    slotName: 'stationName',
    align: 'center',
    width: 150
  },
  {
    title: '所属设备',
    dataIndex: 'deviceName',
    align: 'center',
    width: 120
  },
  {
    title: '报警类型',
    dataIndex: 'categoryName',
    align: 'center',
    width: 120
  },
  {
    title: '报警等级',
    dataIndex: 'triggerLevel',
    slotName: 'triggerLevel',
    align: 'center',
    width: 120
  },
  {
    title: '发生时间',
    dataIndex: 'happenTime',
    align: 'center',
    width: 180
  },
  {
    title: '恢复时间',
    dataIndex: 'recoverTime',
    align: 'center',
    width: 180
  },
  {
    title: '状态',
    dataIndex: 'triggerStatus',
    slotName: 'triggerStatus',
    align: 'center',
    width: 100
  },
  {
    title: '操作',
    dataIndex: 'operations',
    slotName: 'operate',
    align: 'center',
    width: 250
  }
]);

/**
 * 表格页码发生变化
 * @param val
 */
const onPageChange = async (val: number) => {
  pagination.current = val;
  // 重新获取数据
  await fetchData();
};

/**
 * 表格每页数量发生变化
 * @param val 值
 */
const onPageSizeChange = async (val: number) => {
  pagination.pageSize = val;
  // 重新获取数据
  await fetchData();
};

/**
 * 查询表格数据
 */
const fetchData = async () => {
  setLoading(true);
  const res: any = await listTrigger({
    pageSize: pagination.pageSize,
    pageNum: pagination.current,
    // 事件状态
    triggerStatus: searchModel.value.triggerStatus,
    // 报警等级
    triggerLevel: searchModel.value.triggerLevel
  });
  if (res.data.code == 200) {
    renderData.value = res.data.rows;
    pagination.total = res.data.total;
  }
  setLoading(false);
};

onMounted(async () => {
  await fetchData();
});

// 查询
const search = async () => {
  pagination.current = 1;
  await fetchData();
};

// 重置查询
const reset = async () => {
  searchModel.value = generateSearchModel();
  pagination.current = 1;
  await fetchData();
};

// 操作弹框模型
const generateOperateModalModel = () => {
  return {
    visible: false,
    rules: {
      triggerStatus: [{ required: true, message: '请选择事件状态' }]
    },
    formModel: {
      id: 0,
      triggerName: '',
      triggerStatus: undefined,
      recoverTime: ''
    }
  };
};

const operateModalModel = ref(generateOperateModalModel());

/**
 * 提示弹框取消
 */
const handleOperateModelCancle = () => {
  operateModalModel.value = generateOperateModalModel();
};

/**
 * 提示弹框确认
 */
const handleOperateModelOk = () => {
  // 根据ID查询数据并更新状态和恢复时间
  const index = renderData.value.findIndex((item: any) => item.id == operateModalModel.value.formModel.id);
  if (index !== -1) {
    renderData.value[index].triggerStatus = operateModalModel.value.formModel.triggerStatus;
    renderData.value[index].recoverTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
  }
};

/**
 * 确认按钮处理
 */
const handleConfirm = async (val: any) => {
  operateModalModel.value.visible = true;
  operateModalModel.value.formModel.id = val.id;
  operateModalModel.value.formModel.triggerName = val.triggerName;
};

// 表单抽屉模型
const generateFormDrawerModel = () => {
  return {
    visible: false,
    loading: false,
    rules: {},
    formModel: {
      id: 0,
      // 事件名称
      triggerName: '',
      // 所属站点
      stationName: '',
      // 所属设备
      deviceName: '',
      // 变量名称
      varName: '',
      // 变量代码
      varSn: '',
      // 报警类型
      categoryName: '',
      // 报警等级
      triggerLevel: '',
      // 发生时间
      happenTime: '',
      // 恢复时间
      recoverTime: '',
      triggerStatusName: '',
      // 解决人员
      confirmBy: '',
      // 解决过程
      confirmContent: '',
      // 报警内容
      triggerContent: '',
      // 报警状态
      triggerStatus: undefined
    }
  };
};

const formDrawer = ref(generateFormDrawerModel());

// 报警详情数据
const detailDataList = computed<DescData[]>(() => {
  const result: DescData[] = [
    {
      label: '事件名称',
      value: formDrawer.value.formModel.triggerName || '-'
    },
    {
      label: '所属站点',
      value: formDrawer.value.formModel.stationName || '-'
    },
    {
      label: '所属设备',
      value: formDrawer.value.formModel.deviceName || '-'
    },
    {
      label: '变量名称',
      value: formDrawer.value.formModel.varName || '-'
    },
    {
      label: '变量代码',
      value: formDrawer.value.formModel.varSn || '-'
    },
    {
      label: '报警类型',
      value: formDrawer.value.formModel.categoryName || '-'
    },
    {
      label: '报警等级',
      value: formDrawer.value.formModel.triggerLevel == 100 ? '一级报警' : '二级报警'
    },
    {
      label: '报警内容',
      value: formDrawer.value.formModel.triggerContent || '-'
    },
    {
      label: '发生时间',
      value: formDrawer.value.formModel.happenTime || '-'
    },
    {
      label: '恢复时间',
      value: formDrawer.value.formModel.recoverTime || '-'
    },
    {
      label: '报警状态',
      value: formDrawer.value.formModel.triggerStatus == 10 ? '已恢复' : '发生中'
    }
  ];
  return result;
});

/**
 * 表单抽屉取消
 */
const handleFormCancel = () => {
  formDrawer.value = generateFormDrawerModel();
};

/**
 * 查看详情处理
 */
const handleDetail = async (val: any) => {
  formDrawer.value.visible = true;
  formDrawer.value.loading = true;
  formDrawer.value.formModel.id = val.id;
  // 赋值详情数据
  formDrawer.value.formModel = { ...val };
  formDrawer.value.loading = false;
};

/**
 * 创建工单处理
 */
const handleCreateOrder = (record: any) => {
  // 跳转到工单管理页面
  router.push({
    path: '/Operationmanage/WorkOrder',
    query: { triggerId: record.id }
  });
};
</script>